import 'dart:developer';

import 'package:edu/constants/app_regex.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/account/user_api.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class VerifyCodeSubmitPageLogic extends ChangeNotifier {
  static const kResetEmail = 'reset_email';
  static const kResetPhoneNumber = 'reset_phone_number';
  static const kResetPassword = 'reset_password';
  static const kLoginVerifyCode = 'login_verify_code';

  final String submitType;
  final String holdValue;
  final String? prevRoute;

  late final textController = TextEditingController();
  late final focusNode = FocusNode();

  bool get canSubmit => textController.text.length >= 6;

  bool? password1Ready = false;
  bool? password2Ready = false;
  late final passwordController1 = TextEditingController();
  late final passwordController2 = TextEditingController();
  late final focusNode1 = FocusNode();
  late final focusNode2 = FocusNode();
  bool _password1Used = false;
  bool _password2Used = false;

  VerifyCodeSubmitPageLogic({
    required this.submitType,
    required this.holdValue,
    this.prevRoute,
  });

  String get title {
    switch (submitType) {
      case kResetEmail:
        return AppStrings.changeEmail;
      case kResetPhoneNumber:
        return AppStrings.changePhone;
      case kResetPassword:
        return AppStrings.resetPassword;
      case kLoginVerifyCode:
        return AppStrings.verifyCodeLogin;
      default:
        return '';
    }
  }

  void init() {
    textController.addListener(() {
      notifyListeners();
    });

    passwordController1.addListener(() {
      final text1 = passwordController1.text;
      if (text1.isNotEmpty) {
        _password1Used = true;
      } else {
        _password1Used = false;
      }

      if (_password1Used) {
        password1Ready = text1.length >= 8;
      }

      if (_password2Used) {
        final text2 = passwordController2.text;
        password2Ready = text2.length >= 8 && text1 == text2;
      }
      notifyListeners();
    });

    passwordController2.addListener(() {
      final text = passwordController2.text;
      if (text.isNotEmpty) {
        _password2Used = true;
      }
      if (_password2Used) {
        password2Ready = text.length >= 8 && text == passwordController1.text;
      }
      notifyListeners();
    });
  }

  Future<bool> submit() async {
    focusNode.unfocus();
    focusNode1.unfocus();
    focusNode2.unfocus();

    // if (submitType == kLoginVerifyCode) {
    //   return _loginWithVerifyCode();
    // } else if (submitType == kResetEmail) {
    //   return _resetEmail();
    // } else if (submitType == kResetPhoneNumber) {
    //   return _resetPhoneNumber();
    // } else {
    //   return false;
    // }
    switch (submitType) {
      case kResetEmail:
        return _resetEmail();
      case kResetPhoneNumber:
        return _resetPhoneNumber();
      case kResetPassword:
        return _resetPassword();
      case kLoginVerifyCode:
        return _loginWithVerifyCode();
      default:
        return false;
    }
  }

  // 重置邮箱
  Future<bool> _resetEmail() async {
    final code = textController.text;
    if (holdValue == AccountInfo.shared.userProfile?.email) {
      return false;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.updateUserEmail(
        holdValue,
        code,
      );
      EasyLoading.dismiss();
      if (response.code == 0 && response.result?.field == 'email') {
        EasyLoading.showSuccess(AppStrings.updateSuccess);
        AccountInfo.shared.updateEmail(response.result?.value);
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }

  // 重置手机号
  Future<bool> _resetPhoneNumber() async {
    final code = textController.text;
    if (holdValue == AccountInfo.shared.userProfile?.phoneNumber) {
      return false;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.updateUserPhoneNumber(
        holdValue,
        code,
      );
      EasyLoading.dismiss();
      if (response.code == 0 && response.result?.field == 'phone_number') {
        EasyLoading.showSuccess(AppStrings.updateSuccess);
        AccountInfo.shared.updatePhoneNumber(response.result?.value);
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }

  // 验证码登录使用的接口
  Future<bool> _loginWithVerifyCode() async {
    final emailRegex = RegExp(AppRegex.email);
    final phoneRegex = RegExp(AppRegex.phone);
    final account = holdValue;
    final UserLoginType type;

    if (emailRegex.hasMatch(account)) {
      type = UserLoginType.emailVerifyCode;
    } else if (phoneRegex.hasMatch(account)) {
      type = UserLoginType.phoneVerifyCode;
    } else {
      return false;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      final code = textController.text;
      final response = await DataFetcher.shared.userApi.login(
        type: UserApi.getLoginType(type),
        account: account,
        code: code,
      );
      EasyLoading.dismiss();
      if (response.code == 0 &&
          response.token != null &&
          response.brief != null) {
        await AccountInfo.shared.login(response.brief!, response.token!);
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }

  // 重置密码
  Future<bool> _resetPassword() async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );
      final password = passwordController1.text;
      final code = textController.text;
      late final emailRegex = RegExp(AppRegex.email);
      late final phoneRegex = RegExp(AppRegex.phone);
      final type = emailRegex.hasMatch(holdValue)
          ? 'email_code'
          : phoneRegex.hasMatch(holdValue)
          ? 'phone_code'
          : '';
      final response = await DataFetcher.shared.userApi.updateUserPassword(
        type: type,
        account: holdValue,
        password: password,
        code: code,
      );
      EasyLoading.dismiss();
      if (response.code == 0) {
        EasyLoading.showSuccess(AppStrings.updateSuccess);
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
      return false;
    }
  }
}
